package tp.pr5.instructions;

import tp.pr5.Constants;
import tp.pr5.NavigationModule;
import tp.pr5.RobotEngine;
import tp.pr5.instructions.exceptions.InstructionExecutionException;
import tp.pr5.instructions.exceptions.WrongInstructionFormatException;
import tp.pr5.items.Item;
import tp.pr5.items.ItemContainer;

public class TriggerInstruction implements Instruction
{
	private String id;
	private RobotEngine engine;
	private NavigationModule navigation; 
	
	public TriggerInstruction()
	{
		// TODO Auto-generated constructor stub
	}
	
	public TriggerInstruction(String id)
	{
		this.id = id;
	}

	@Override
	public Instruction parse(String cad) throws WrongInstructionFormatException 
	{
		String[] entry = cad.trim().split(" +");
		if((entry[0].toUpperCase().equals("TRIGGER") || entry[0].toUpperCase().equals("ACTIVAR")) && entry.length == 1)
		{
			throw new WrongInstructionFormatException(); 
		}
		if((entry[0].toUpperCase().equals("TRIGGER") || entry[0].toUpperCase().equals("ACTIVAR")) && entry.length == 2)
		{
			return new TriggerInstruction(entry[1]);
		}
		throw new WrongInstructionFormatException();
	}

	@Override
	public String getHelp() 
	{
		return "TRIGGER|ACTIVAR";
	}

	@Override
	public void configureContext(RobotEngine engine, NavigationModule navigation, ItemContainer robotContainer) 
	{
		this.engine = engine;
		this.navigation = navigation;
	}

	@Override
	public void execute() throws InstructionExecutionException 
	{
		Item item = this.navigation.getCurrentPlace().getItem(this.id);
		
		if(item != null)
		{
			if(!item.canBeDefused())
			{
				if(item.use(this.engine, this.navigation))
				{	
					this.engine.saySomething(Constants.MESSAGE_TRIGGER_OK.replace("{ID}", this.id));
				}
				else
				{
					throw new InstructionExecutionException(Constants.MESSAGE_TRIGGER_ERROR.replace("{ID}", this.id));
				}
			}
			else
			{
				throw new InstructionExecutionException(Constants.MESSAGE_TRIGGER_ERROR.replace("{ID}", this.id));
			}
		}
		else
		{
			throw new InstructionExecutionException(Constants.MESSAGE_DEFUSE_ERROR2.replace("{ID}", this.id));
		}

	}

}
